﻿using System;
using System.Data.Sql;
using Microsoft.SqlServer.Server;
using System.Collections;
using System.Data.SqlTypes;
using System.Diagnostics;


public class ClrEventLog
{

    [SqlFunction(FillRowMethodName = "FillRow")]
    public static IEnumerable GetEventLog(String logname)
    {
        // to avoid error=> System.Security.SecurityException: Requested registry access is not allowed.  
        if (logname == "Security")
            return null;
        else if (EventLog.Exists(logname))
        {
            return new EventLog(logname).Entries;
        }
        else
            return null;
    }

    public static void FillRow( Object obj
                                , out SqlDateTime Logged
                                , out SqlChars Message
                                , out SqlChars TaskCategory
                                , out long EventID
                                , out SqlString Level
                                , out SqlString User
                                , out SqlString Computer
                                , out SqlString Source)
    {
            EventLogEntry eventLogEntry = (EventLogEntry)obj;

            Source = new SqlString(eventLogEntry.Source);
            User = new SqlString(eventLogEntry.UserName);
            Computer = new SqlString(eventLogEntry.MachineName);
            Logged = new SqlDateTime(eventLogEntry.TimeWritten);
            Message = new SqlChars(eventLogEntry.Message);
            TaskCategory = new SqlChars(eventLogEntry.Category);
            EventID = eventLogEntry.InstanceId;
            Level = eventLogEntry.EntryType.ToString();
    } /*end function FillRow*/

} /*end class ClrEventLog*/

